﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace syc.Sale
{
    public partial class HeTong_Sale : System.Web.UI.Page
    {
        //初始化
        protected void Page_Load(object sender, EventArgs e)
        {
            int BillID = 0;
            if (!this.IsPostBack)
            {
                this.DZList.DataBind();             
                this.GJList.DataBind();
                this.GGList.DataBind();
                this.LWList.DataBind();
                this.CDList.DataBind();
                this.DingHuo.DataBind();
                this.ShouHuo.DataBind();
                this.ChanPin.DataBind();
                this.JingBan.DataBind();
                this.ZhuGuan.DataBind();
                this.FaHuo.DataBind();
                DingHuo_SelectedIndexChanged(null, null);
                ShouHuo_SelectedIndexChanged(null, null);
                ChanPin_SelectedIndexChanged(null, null);

                //如有有传入参数，则读取相应的ID的合同内容
                if (Request.QueryString["ID"] != null)
                {
                    int.TryParse(Request.QueryString["ID"], out BillID);
                }
                if (BillID > 0)
                {
                    SqlConnection Conn = new SqlConnection();
                    Conn.ConnectionString = ConfigurationManager.ConnectionStrings["SCMConnectionString1"].ConnectionString;
                    Conn.Open();
                    SqlCommand Cmd = new SqlCommand();
                    Cmd.Connection = Conn;
                    Cmd.CommandText = @"select [订货单位ID], [收货单位ID], [产品ID], [合同编号], 
                                               [数量], [运输方式], [经办人], [部门主管], [备注], [日期],[金额] 
                                        from [产品销售合同] where [ID]=" + BillID;
                    Cmd.CommandType = CommandType.Text;
                    SqlDataReader Reader = Cmd.ExecuteReader();
                    if (Reader.Read())
                    {
                        this.ViewState["BillID"] = BillID;
                        this.RiQi.Text = Reader.GetDateTime(9).ToString("yyyy年M月d日");
                        this.HeTongHao.Text = Reader.GetString(3).Trim();
                        this.HeTongHao.ReadOnly = false;
                        this.HeTongHao.CssClass = "intxt1";
                        this.DingHuoLiang.Text = Reader.GetFloat(4).ToString();
                        this.BeiZhu.Text = Reader.GetString(8).Trim();
                        this.Jine.Text = Reader.GetDecimal(10).ToString();
                        string t;
                        t = Reader.GetInt32(0).ToString();
                        if (this.DingHuo.Items.FindByValue(t)!=null)
                        {
                            this.DingHuo.Text = t;
                            this.DingHuoDiZhi.Text = this.DZList.Items.FindByValue(t).Text;
                        }

                        t = Reader.GetInt32(1).ToString();
                        if (this.ShouHuo.Items.FindByValue(t) != null)
                        {
                            this.ShouHuo.Text = t;
                            this.ShouHuoDiZhi.Text = this.DZList.Items.FindByValue(t).Text;
                        }
                        t = Reader.GetInt32(2).ToString();
                        if (this.ChanPin.Items.FindByValue(t) != null)
                        {
                            this.ChanPin.Text = t;
                            this.GangJi.Text = this.GJList.Items.FindByValue(t).Text;
                            this.GuiGe.Text = this.GGList.Items.FindByValue(t).Text;
                            this.LuoWen.Text = this.LWList.Items.FindByValue(t).Text;
                            this.ChangDu.Text = this.CDList.Items.FindByValue(t).Text;
                        }
                        t = Reader.GetString(5).Trim();
                        if (this.FaHuo.Items.FindByValue(t) != null)
                        {
                            this.FaHuo.Text = t;
                        }
                        t = Reader.GetString(6).Trim();
                        if (this.JingBan.Items.FindByValue(t) != null)
                        {
                            this.JingBan.Text = t;
                        }
                        t = Reader.GetString(7).Trim();
                        if (this.ZhuGuan.Items.FindByValue(t) != null)
                        {
                            this.ZhuGuan.Text = t;
                        }
                        Reader.Close();
                    }
                    else
                    {
                        this.RiQi.Text = DateTime.Today.ToString("yyyy年M月d日");
                        Reader.Close();
                    }

                    Conn.Close();
                    Reader.Dispose();
                    Cmd.Dispose();
                    Conn.Dispose();
                }
                else
                {
                    this.RiQi.Text = DateTime.Today.ToString("yyyy年M月d日");
                }
            }
            this.Message.Text = "·准备就绪";
        }

        //订货单位下拉列表变化时的处理函数
        protected void DingHuo_SelectedIndexChanged(object sender, EventArgs e)
        {
           // ShouHuo.SelectedIndex = DingHuo.SelectedIndex;
            this.DingHuoDiZhi.Text = DZList.Items.FindByValue(this.DingHuo.Text).Text;
            this.ShouHuoDiZhi.Text = DZList.Items.FindByValue(this.ShouHuo.Text).Text;
            
            //设置合同编号子函数
            SetHTHao();
        }
        /// <summary>
        /// 通过订货单位、套管油管、合同序号、以及日期生成一个合同编号
        /// </summary>
        private void SetHTHao() {
            //去拼音首字母子函数的调用
            var dz = DingHuo.SelectedItem.Text;
            //油管还是套管
            var cp = ChanPin.SelectedValue;
            var cp1 = "";
            if (cp == "1" || cp=="3") { cp1 = "Y"; } else { cp1 = "T"; }
            dz = dz.Replace("采油厂", "");
            //得到该合同在当年的序号
            var XuHao = GetNumber();
            //规则为【拼音首字母】-【Y/T】-【该合同在当年的序号】-【yyMM】
            dz = GetPYString(dz).ToUpper() + "-" + cp1 + "-" + XuHao + "-" + DateTime.Now.ToString("yyMM");
            this.HeTongHao.Text = dz;
        }

        /// <summary>
        /// 返回该合同的在当年的序号
        /// </summary>
        /// <returns></returns>
        public string GetNumber()
        {
            //取产品
            var cp = ChanPin.SelectedValue;
            //数据库中取出唯一上一个ID编号的合同编号
            SqlDataSource10.SelectCommand = @"
            SELECT TOP 1 ID,合同编号
            FROM 产品销售合同
            WHERE 产品ID=" + cp + "AND YEAR(日期)=" + DateTime.Now.Year + "ORDER BY ID DESC";
            DropDownList1.DataBind();
            var re = DropDownList1.SelectedValue;
            //取得返回值后，将合同号用“-”号拆分，最后去下标【2】，即上一张合同的序号
            string[] r = re.Split(new Char[] { '-' });
            if (r.Length != 4) { r = "XX-YY-000-001".Split(new Char[] { '-' }); }
            int r2 = 0;
            string rr = "";
            //解析取得的上一个序号，加一，并格式化成002类似格式
            if (int.TryParse(r[2], out r2)) { rr = (r2 + 1).ToString("000"); } else { rr = "001"; }
            return rr;
        }

        //收货合同下拉列表变化时的处理函数
        protected void ShouHuo_SelectedIndexChanged(object sender, EventArgs e)
        {
           // DingHuo.SelectedIndex = ShouHuo.SelectedIndex;
            this.DingHuoDiZhi.Text = DZList.Items.FindByValue(this.DingHuo.Text).Text;
            this.ShouHuoDiZhi.Text = DZList.Items.FindByValue(this.ShouHuo.Text).Text;
        }

        //产品变化时的处理函数
        protected void ChanPin_SelectedIndexChanged(object sender, EventArgs e)
        {
            string id = this.ChanPin.Text;
            this.GangJi.Text = this.GJList.Items.FindByValue(id).Text;
            this.GuiGe.Text = this.GGList.Items.FindByValue(id).Text;
            this.LuoWen.Text = this.LWList.Items.FindByValue(id).Text;
            this.ChangDu.Text=this.CDList.Items.FindByValue(id).Text;
            SetHTHao();
        }

        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button_Finish_Click(object sender, EventArgs e)
        {
            DateTime dt;
            float dhl;
            Decimal jine;
            if (!DateTime.TryParse(this.RiQi.Text, out dt))
            {
                this.Message.Text = "·日期输入有误";
                return;
            }
            if (!float.TryParse(this.DingHuoLiang.Text, out dhl))
            {
                this.Message.Text = "·订货量输入有误";
                return;
            }
            if (!Decimal.TryParse(this.Jine.Text, out jine))
            {
                this.Message.Text = "·订货金额输入有误";
                return;
            }
            if (this.HeTongHao.Text.Trim().Length==0)
            {
                this.Message.Text = "·合同号必须录入";
                return;
            }
            SqlConnection Conn = new SqlConnection();
            Conn.ConnectionString = ConfigurationManager.ConnectionStrings["SCMConnectionString1"].ConnectionString;
            Conn.Open();
            SqlTransaction Tran = Conn.BeginTransaction();
            SqlCommand Cmd = new SqlCommand();
            Cmd.Connection = Conn;
            Cmd.Transaction = Tran;
            try
            {
                Cmd.CommandText = "HeTong_Sale";
                Cmd.CommandType = CommandType.StoredProcedure;
                if (this.ViewState["BillID"] == null)
                {
                    this.ViewState["BillID"] = -1;
                }
                Cmd.Parameters.Add(new SqlParameter("@订货单位ID", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, int.Parse(this.DingHuo.Text)));
                Cmd.Parameters.Add(new SqlParameter("@收货单位ID", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, int.Parse(this.ShouHuo.Text)));
                Cmd.Parameters.Add(new SqlParameter("@产品ID", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, int.Parse(this.ChanPin.Text)));
                Cmd.Parameters.Add(new SqlParameter("@合同编号", SqlDbType.Char, 20, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, this.HeTongHao.Text));
                Cmd.Parameters.Add(new SqlParameter("@数量", SqlDbType.Real, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, dhl));
                Cmd.Parameters.Add(new SqlParameter("@金额", SqlDbType.Decimal, 20, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, jine));
                Cmd.Parameters.Add(new SqlParameter("@运输方式", SqlDbType.NChar, 20, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, this.FaHuo.Text));
                Cmd.Parameters.Add(new SqlParameter("@经办人", SqlDbType.NChar, 20, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, this.JingBan.Text));
                Cmd.Parameters.Add(new SqlParameter("@部门主管", SqlDbType.NChar, 20, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, this.ZhuGuan.Text));
                Cmd.Parameters.Add(new SqlParameter("@备注", SqlDbType.NVarChar, 400, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, this.BeiZhu.Text));
                Cmd.Parameters.Add(new SqlParameter("@日期", SqlDbType.Date, 3, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, DateTime.Parse(RiQi.Text)));
                Cmd.Parameters.Add(new SqlParameter("@BillID", SqlDbType.Int, 4, ParameterDirection.Input, true, 0, 0, "", DataRowVersion.Proposed, this.ViewState["BillID"]));
                Cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int, 4, ParameterDirection.Output, true, 0, 0, "", DataRowVersion.Proposed, null));

                Cmd.ExecuteNonQuery();

                this.ViewState["BillID"] = (int)Cmd.Parameters["@ID"].Value;
                int BillID = (int)this.ViewState["BillID"];
                if (BillID > 0)
                {
                    this.HeTongHao.CssClass = "blank_left";
                    this.Message.Text = "·保存成功";
                }
                else
                {
                    this.Message.Text = "·合同编号已经存在";
                }
                Tran.Commit();
            }
            catch (Exception err)
            {
                Tran.Rollback();
                this.Message.Text = err.Message;
            }
            Cmd.Dispose();
            Tran.Dispose();
            Conn.Close();
            Conn.Dispose();
        }

        /// <summary>
        /// 合同管理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button2_Click(object sender, EventArgs e)
        {
            Response.Redirect("HeTong_Sale_Search.aspx");
        }
        /// <summary>
        /// 新建合同
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Button_New_Click(object sender, EventArgs e)
        {
            Response.Redirect("HeTong_Sale.aspx");
        }


		/// <summary>
		/// 汉字转拼音缩写
		/// </summary>/// <param name="str">要转换的汉字字符串</param>
		/// /// <returns>拼音缩写</returns>
		public string GetPYString(string str)
		{
			string tempStr = "";
			foreach (char c in str)
			{
				if ((int)c >= 33 && (int)c <= 126)
				{//字母和符号原样保留           
					tempStr += c.ToString();
				}
				else
				{//累加拼音声母     
					tempStr += GetPYChar(c.ToString());
				}
			}
			return tempStr;
		}
		/// <summary>
		/// /// 取单个字符的拼音声母/// Code By MuseStudio@hotmail.com
		/// /// 2004-11-30/// </summary>/// <param name="c">要转换的单个汉字</param>
		/// /// <returns>拼音声母</returns>
		public string GetPYChar(string c)
		{
			byte[] array = new byte[2];
			array = System.Text.Encoding.Default.GetBytes(c);
			int i = (short)(array[0] - '\0') * 256 + ((short)(array[1] - '\0'));
			if (i < 0xB0A1) return "*";
			if (i < 0xB0C5) return "a";
			if (i < 0xB2C1) return "b";
			if (i < 0xB4EE) return "c";
			if (i < 0xB6EA) return "d";
			if (i < 0xB7A2) return "e";
			if (i < 0xB8C1) return "f";
			if (i < 0xB9FE) return "g";
			if (i < 0xBBF7) return "h";
			if (i < 0xBFA6) return "g";
			if (i < 0xC0AC) return "k";
			if (i < 0xC2E8) return "l";
			if (i < 0xC4C3) return "m";
			if (i < 0xC5B6) return "n";
			if (i < 0xC5BE) return "o";
			if (i < 0xC6DA) return "p";
			if (i < 0xC8BB) return "q";
			if (i < 0xC8F6) return "r";
			if (i < 0xCBFA) return "s";
			if (i < 0xCDDA) return "t";
			if (i < 0xCEF4) return "w";
			if (i < 0xD1B9) return "x";
			if (i < 0xD4D1) return "y";
			if (i < 0xD7FA) return "z";
			return "*";
		}    
    }
}
